package com.wxfbboy.suanfa.utils;

import java.lang.reflect.Array;
import java.util.Arrays;

public class BinarySearch {

    public static int BinarySearch(int[] arr , int key){
        Arrays.sort(arr);
        int low = 0;
        int high = arr.length - 1;
        return BinarySearch( arr , key , low , high );
    }

    public static int BinarySearch( int[] arr , int key , int low , int high ){
        if( key < arr[low] || key > arr[high] || low > high ){
            return -1;
        }
        int middle = ( low + high ) / 2 ;
        if( arr[middle] > key ){
            return BinarySearch( arr , key , low , middle - 1);
        }
        else if( arr[middle] < key ){
            return BinarySearch( arr , key , middle + 1 , high);
        }
        else if( arr[middle] == key ){
            return middle;
        }
        else{
            return -1;
        }
    }
}
